#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <linux/fb.h>
#include <time.h>
#include <ft2build.h>
#include <png.h>
#include <gif_lib.h>
#include FT_FREETYPE_H
#include <dirent.h>

// 帧缓冲结构体
typedef struct {
    int fd;
    char *map;
    struct fb_var_screeninfo var_info;
    int width;
    int height;
    int bpp;
    int bytes_per_pixel;
    long screen_size;
    char *back_buffer;
} FrameBuffer;

// 字体渲染结构体
typedef struct {
    FT_Library library;
    FT_Face face;
    FT_Face chinese_face;  // 新增中文字体
} FontRenderer;

// 图片结构体
typedef struct {
    int width;
    int height;
    unsigned char *data;
} Image;

// 初始化帧缓冲
int fb_init(FrameBuffer *fb, const char *device) {
    fb->fd = open(device, O_RDWR);
    if (fb->fd < 0) {
        perror("无法打开帧缓冲设备");
        return -1;
    }

    if (ioctl(fb->fd, FBIOGET_VSCREENINFO, &fb->var_info) < 0) {
        perror("无法获取屏幕信息");
        close(fb->fd);
        return -1;
    }

    fb->width = fb->var_info.xres;
    fb->height = fb->var_info.yres;
    fb->bpp = fb->var_info.bits_per_pixel;
    fb->bytes_per_pixel = fb->bpp / 8;
    fb->screen_size = fb->width * fb->height * fb->bytes_per_pixel;

    fb->map = mmap(NULL, fb->screen_size, PROT_READ | PROT_WRITE, MAP_SHARED, fb->fd, 0);
    if (fb->map == MAP_FAILED) {
        perror("无法映射帧缓冲");
        close(fb->fd);
        return -1;
    }

    // 分配后备缓冲区
    fb->back_buffer = malloc(fb->screen_size);
    if (!fb->back_buffer) {
        perror("无法分配后备缓冲区");
        munmap(fb->map, fb->screen_size);
        close(fb->fd);
        return -1;
    }

    printf("屏幕分辨率: %dx%d, 色深: %d位\n", fb->width, fb->height, fb->bpp);
    return 0;
}

// 关闭帧缓冲
void fb_close(FrameBuffer *fb) {
    if (fb->back_buffer) free(fb->back_buffer);
    if (fb->map) munmap(fb->map, fb->screen_size);
    if (fb->fd >= 0) close(fb->fd);
}

// 在后备缓冲区写入像素
void fb_write_pixel(FrameBuffer *fb, int x, int y, unsigned char r, unsigned char g, unsigned char b) {
    // 垂直翻转
    int mirrored_y = fb->height - 1 - y;
    
    if (x >= 0 && x < fb->width && mirrored_y >= 0 && mirrored_y < fb->height) {
        long pos = (mirrored_y * fb->width + x) * fb->bytes_per_pixel;
        
        if (fb->bpp == 16) {
            // RGB565格式
            unsigned short rgb565 = ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3);
            *((unsigned short*)(fb->back_buffer + pos)) = rgb565;
        } else {
            // 假设32位色BGRA格式
            fb->back_buffer[pos] = b;
            fb->back_buffer[pos+1] = g;
            fb->back_buffer[pos+2] = r;
            fb->back_buffer[pos+3] = 0xFF; // Alpha通道
        }
    }
}
// 修改字体加载函数，添加权限检查
int load_font_with_permission_check(FT_Library library, const char* font_path, FT_Face* face) {
    // 检查文件是否存在
    if (access(font_path, F_OK) != 0) {
        fprintf(stderr, "字体文件不存在: %s\n", font_path);
        return -1;
    }
    
    // 检查文件可读权限
    if (access(font_path, R_OK) != 0) {
        fprintf(stderr, "无读取字体文件权限: %s\n", font_path);
        return -1;
    }
    
    // 尝试加载字体
    int error = FT_New_Face(library, font_path, 0, face);
    if (error) {
        fprintf(stderr, "字体加载失败(错误代码 %d): %s\n", error, font_path);
        return -1;
    }
    
    return 0;
}
// 查找系统字体目录中的中文字体
const char* find_system_chinese_font() {
    // 常见的中文字体文件名
    const char* chinese_fonts[] = {
        "DejaVuSerif.ttf",
        "NotoSansCJK-Regular.ttf",  // Google Noto字体
        "DroidSansFallback.ttf",    // Android字体
        "WenQuanYiMicroHei.ttf",    // 文泉驿微米黑
        "uming.ttc",                // 文鼎字体
        "ukai.ttc",                 // 文鼎字体
        "simsun.ttc",               // 宋体
        "msyh.ttf",                 // 微软雅黑
        "simhei.ttf",               // 黑体
        NULL
    };

    // 常见的系统字体目录
    const char* font_dirs[] = {
        "/usr/share/fonts/",
        "/usr/local/share/fonts/",
        "/usr/X11R6/lib/X11/fonts/",
        "/usr/lib/X11/fonts/",
        "/usr/share/fonts/truetype/noto/",
        "/usr/share/fonts/opentype/",
        "/usr/share/fonts/chinese/",
        "/usr/share/fonts/zh_CN/",
        "/usr/share/fonts/TTF/",
        "/usr/share/fonts/OTF/",
        "/usr/share/wine/fonts/",
        "/usr/local/share/fonts/truetype/",
        "/usr/local/share/fonts/opentype/",
        "/usr/local/share/fonts/chinese/",
        "/usr/local/share/fonts/zh_CN/",
        "/usr/local/share/fonts/TTF/",
        "/usr/local/share/fonts/OTF/",
        NULL
    };

    // 遍历字体目录
    for (int i = 0; font_dirs[i] != NULL; i++) {
        DIR *dir = opendir(font_dirs[i]);
        if (dir == NULL) continue;

        struct dirent *entry;
        while ((entry = readdir(dir)) != NULL) {
            // 检查是否是字体文件
            for (int j = 0; chinese_fonts[j] != NULL; j++) {
                if (strstr(entry->d_name, chinese_fonts[j]) != NULL) {
                    // 构建完整路径
                    static char full_path[512];
                    snprintf(full_path, sizeof(full_path), "%s%s", font_dirs[i], entry->d_name);
                    closedir(dir);
                    return full_path;
                }
            }
        }
        closedir(dir);
    }

    return NULL; // 没有找到中文字体
}
int font_init(FontRenderer *fr, const char *font_path) {
    if (FT_Init_FreeType(&fr->library)) {
        fprintf(stderr, "FreeType初始化失败\n");
        return -1;
    }

    // 加载英文字体
    printf("尝试加载字体: %s\n", font_path);
    if (load_font_with_permission_check(fr->library, font_path, &fr->face)) {
        FT_Done_FreeType(fr->library);
        return -1;
    }

    // 查找中文字体
    const char *chinese_font_path = find_system_chinese_font();
    if (chinese_font_path == NULL) {
        fprintf(stderr, "未找到系统内置中文字体\n");
        fr->chinese_face = NULL;
    } else {
        printf("找到中文字体: %s\n", chinese_font_path);
        if (load_font_with_permission_check(fr->library, chinese_font_path, &fr->chinese_face)) {
            fprintf(stderr, "中文字体加载失败，使用英文字体回退\n");
            fr->chinese_face = NULL;
        }
    }

    return 0;
}
const char* find_system_chinese_font_debug() {
    const char* chinese_fonts[] = {
        "HarmonyOS_Sans_SC_Regular.ttf",
        "NotoSansCJK-Regular.ttf",  // Google Noto字体
        "DroidSansFallback.ttf",    // Android字体
        "WenQuanYiMicroHei.ttf",    // 文泉驿微米黑
        "uming.ttc",                // 文鼎字体
        "ukai.ttc",                 // 文鼎字体
        "simsun.ttc",               // 宋体
        "msyh.ttf",                 // 微软雅黑
        "simhei.ttf",               // 黑体
        NULL
    };

    const char* font_dirs[] = {
        "/usr/share/fonts/", "/usr/local/share/fonts/","/usr/share/fonts/truetype/noto/",
        "/usr/share/fonts/truetype/", "/usr/share/fonts/opentype/",
        "/opt/aku/xiaozhi/font/", "/usr/share/fonts/truetype/dejavu/",
        "/usr/share/fonts/TTF/", "/usr/share/fonts/OTF/",
        "/usr/local/share/fonts/truetype/", 
        "/usr/local/share/fonts/opentype/",
        NULL
    };

    printf("\n=== 开始扫描系统字体 ===\n");
    
    for (int i = 0; font_dirs[i] != NULL; i++) {
        printf("扫描目录: %s\n", font_dirs[i]);
        
        DIR *dir = opendir(font_dirs[i]);
        if (dir == NULL) {
            printf("无法打开目录: %s\n", font_dirs[i]);
            continue;
        }

        struct dirent *entry;
        while ((entry = readdir(dir)) != NULL) {
            if (entry->d_type != DT_REG && entry->d_type != DT_LNK) 
                continue;
                
            for (int j = 0; chinese_fonts[j] != NULL; j++) {
                static char full_path[512];
                snprintf(full_path, sizeof(full_path), "%s%s", font_dirs[i], entry->d_name);

                printf("搜索候选字体: %s\n", full_path);
                if (strstr(entry->d_name, chinese_fonts[j]) != NULL) {
                    static char full_path[512];
                    snprintf(full_path, sizeof(full_path), "%s%s", font_dirs[i], entry->d_name);
                    
                    printf("找到候选字体: %s\n", full_path);
                    
                    // 检查文件权限
                    if (access(full_path, R_OK) == 0) {
                        printf("字体可用: %s\n", full_path);
                        closedir(dir);
                        return full_path;
                    } else {
                        printf("无读取权限: %s\n", full_path);
                    }
                }
            }
        }
        closedir(dir);
    }
    
    printf("=== 扫描完成，未找到可用中文字体 ===\n");
    return NULL;
}

// 增强版字体加载函数
int load_font_debug(FT_Library library, const char* path, FT_Face* face, const char* type) {
    printf("\n尝试加载%s字体: %s\n", type, path);
    
    if (access(path, F_OK) != 0) {
        printf("错误: 文件不存在\n");
        return -1;
    }
    
    if (access(path, R_OK) != 0) {
        printf("错误: 无读取权限\n");
        return -1;
    }
    
    int error = FT_New_Face(library, path, 0, face);
    if (error == FT_Err_Unknown_File_Format) {
        printf("错误: 不支持的字体格式\n");
    } else if (error) {
        printf("错误: 加载失败 (错误代码 %d)\n", error);
    } else {
        printf("成功加载 %s 字体\n", type);
        printf("字体家族: %s\n", (*face)->family_name);
        printf("字体样式: %s\n", (*face)->style_name);
        printf("支持字符集: %d\n", (*face)->num_charmaps);
        
        // 打印支持的字符集
        for (int i = 0; i < (*face)->num_charmaps; i++) {
            FT_CharMap charmap = (*face)->charmaps[i];
            printf("  - 编码: %d, 平台ID: %d, 编码ID: %d\n", 
                  charmap->encoding, charmap->platform_id, charmap->encoding_id);
        }
    }
    
    return error;
}

// 增强版字体初始化
int font_init_debug(FontRenderer *fr, const char *font_path) {
    printf("\n=== 初始化字体系统 ===\n");
    
    if (FT_Init_FreeType(&fr->library)) {
        printf("错误: FreeType初始化失败\n");
        return -1;
    }
    printf("FreeType初始化成功\n");

    // 加载主字体
    if (load_font_debug(fr->library, font_path, &fr->face, "主") != 0) {
        FT_Done_FreeType(fr->library);
        return -1;
    }

    // 查找并加载中文字体
    const char *chinese_path = find_system_chinese_font_debug();
    if (chinese_path) {
        if (load_font_debug(fr->library, chinese_path, &fr->chinese_face, "中文") != 0) {
            printf("警告: 中文字体加载失败，将使用主字体显示中文\n");
            fr->chinese_face = NULL;
        }
    } else {
        printf("警告: 未找到系统中文ttf字体\n");
        fr->chinese_face = NULL;
    }

    printf("=== 字体初始化完成 ===\n\n");
    return 0;
}
// 清空后备缓冲区
void fb_clear_back_buffer(FrameBuffer *fb, unsigned char r, unsigned char g, unsigned char b) {
    if (fb->bpp == 16) {
        unsigned short rgb565 = ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3);
        unsigned short *p = (unsigned short*)fb->back_buffer;
        for (long i = 0; i < fb->width * fb->height; i++) {
            p[i] = rgb565;
        }
    } else {
        // 32位色
        for (long i = 0; i < fb->screen_size; i += 4) {
            fb->back_buffer[i] = b;
            fb->back_buffer[i+1] = g;
            fb->back_buffer[i+2] = r;
            fb->back_buffer[i+3] = 0xFF;
        }
    }
}

// 更新屏幕显示
void fb_update_screen(FrameBuffer *fb) {
    memcpy(fb->map, fb->back_buffer, fb->screen_size);
}



// 关闭字体渲染器
void font_close(FontRenderer *fr) {
    if (fr->face) FT_Done_Face(fr->face);
    if (fr->chinese_face) FT_Done_Face(fr->chinese_face);
    if (fr->library) FT_Done_FreeType(fr->library);
}

// 绘制文本（支持中文）
void draw_text(FrameBuffer *fb, FontRenderer *fr, const char *text, int x, int y, 
               unsigned char r, unsigned char g, unsigned char b, int font_size, int is_chinese) {
    FT_Face face = is_chinese ? fr->chinese_face : fr->face;
    FT_Set_Char_Size(face, 0, font_size * 64, 96, 96);
    
    int pen_x = x;
    int pen_y = y + font_size; // 基线位置
    
    for (int i = 0; text[i] != '\0'; ) {
        unsigned long unicode_char;
        int char_len;
        
        // 判断是否是ASCII字符
        if ((text[i] & 0x80) == 0) {
            // ASCII字符
            unicode_char = text[i];
            char_len = 1;
        } else {
            // 中文字符（UTF-8编码）
            if ((text[i] & 0xE0) == 0xC0) {
                unicode_char = ((text[i] & 0x1F) << 6) | (text[i+1] & 0x3F);
                char_len = 2;
            } else if ((text[i] & 0xF0) == 0xE0) {
                unicode_char = ((text[i] & 0x0F) << 12) | ((text[i+1] & 0x3F) << 6) | (text[i+2] & 0x3F);
                char_len = 3;
            } else {
                // 不支持的编码，跳过
                i++;
                continue;
            }
        }
        
        if (FT_Load_Char(face, unicode_char, FT_LOAD_RENDER | FT_LOAD_TARGET_MONO)) {
            i += char_len;
            continue;
        }
        
        FT_GlyphSlot glyph = face->glyph;
        FT_Bitmap bitmap = glyph->bitmap;
        
        for (int row = 0; row < bitmap.rows; row++) {
            for (int col = 0; col < bitmap.width; col++) {
                int byte_pos = row * bitmap.pitch + col / 8;
                int bit_pos = 7 - (col % 8);
                int pixel = bitmap.buffer[byte_pos] & (1 << bit_pos);
                
                if (pixel) {
                    fb_write_pixel(fb, 
                                  pen_x + col + glyph->bitmap_left,
                                  pen_y - row + glyph->bitmap_top,
                                  r, g, b);
                }
            }
        }
        
        pen_x += glyph->advance.x >> 6;
        i += char_len;
    }
}

// 绘制带透明度的图片
void draw_image(FrameBuffer *fb, Image *img, int x, int y) {
    for (int py = 0; py < img->height; py++) {
        for (int px = 0; px < img->width; px++) {
            int pos = ((img->height - 1 - py) * img->width + px) * 4;
            unsigned char r = img->data[pos];
            unsigned char g = img->data[pos+1];
            unsigned char b = img->data[pos+2];
            unsigned char a = img->data[pos+3];
            
            if (a > 0) {
                if (a == 255) {
                    fb_write_pixel(fb, x + px, y + py, r, g, b);
                } else {
                    // 获取背景颜色（这里简化处理，实际应该读取当前像素值）
                    // 这里假设背景是黑色(0,0,0)作为示例
                    unsigned char bg_r = 0, bg_g = 0, bg_b = 0;
                    
                    // Alpha混合
                    unsigned char final_r = (r * a + bg_r * (255 - a)) / 255;
                    unsigned char final_g = (g * a + bg_g * (255 - a)) / 255;
                    unsigned char final_b = (b * a + bg_b * (255 - a)) / 255;
                    
                    fb_write_pixel(fb, x + px, y + py, final_r, final_g, final_b);
                }
            }
        }
    }
}

// 释放图片资源
void free_image(Image *img) {
    if (img) {
        if (img->data) free(img->data);
        free(img);
    }
}

// 读取电池状态
int read_battery_status(char *status, int *capacity) {
    FILE *fp;
    
    // 读取充电状态
    fp = fopen("/sys/class/power_supply/axp20x-battery/status", "r");
    if (!fp) return -1;
    
    if (fgets(status, 32, fp) == NULL) {
        fclose(fp);
        return -1;
    }
    fclose(fp);
    
    // 去除换行符
    status[strcspn(status, "\n")] = '\0';
    
    // 读取电量百分比
    fp = fopen("/sys/class/power_supply/axp20x-battery/capacity", "r");
    if (!fp) return -1;
    
    if (fscanf(fp, "%d", capacity) != 1) {
        fclose(fp);
        return -1;
    }
    fclose(fp);
    
    return 0;
}

// 加载PNG图片（使用libpng库）
Image* load_png(const char *filename) {
    FILE *fp = fopen(filename, "rb");
    if (!fp) {
        fprintf(stderr, "无法打开PNG文件: %s\n", filename);
        return NULL;
    }

    png_structp png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
    if (!png) {
        fclose(fp);
        return NULL;
    }

    png_infop info = png_create_info_struct(png);
    if (!info) {
        png_destroy_read_struct(&png, NULL, NULL);
        fclose(fp);
        return NULL;
    }

    if (setjmp(png_jmpbuf(png))) {
        png_destroy_read_struct(&png, &info, NULL);
        fclose(fp);
        return NULL;
    }

    png_init_io(png, fp);
    png_read_info(png, info);

    Image *img = malloc(sizeof(Image));
    if (!img) {
        png_destroy_read_struct(&png, &info, NULL);
        fclose(fp);
        return NULL;
    }

    img->width = png_get_image_width(png, info);
    img->height = png_get_image_height(png, info);
    img->data = malloc(img->width * img->height * 4);

    png_set_expand(png);
    png_set_strip_16(png);
    png_set_gray_to_rgb(png);
    png_set_add_alpha(png, 0xff, PNG_FILLER_AFTER);
    png_read_update_info(png, info);

    png_bytep *row_pointers = malloc(sizeof(png_bytep) * img->height);
    for (int y = 0; y < img->height; y++) {
        row_pointers[y] = (png_bytep)(img->data + y * img->width * 4);
    }

    png_read_image(png, row_pointers);
    png_read_end(png, NULL);

    free(row_pointers);
    png_destroy_read_struct(&png, &info, NULL);
    fclose(fp);

    return img;
}

// 获取中文星期名称
const char* get_chinese_weekday(int wday) {
    static const char* weekdays[] = {
        "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"
    };
    if (wday >= 0 && wday < 7) {
        return weekdays[wday];
    }
    return "?";
}

// 显示时间和电池状态
void show_time_and_battery(FrameBuffer *fb, FontRenderer *fr, Image *charging_icon, Image *battery_icon) {
    time_t now;
    struct tm *tm_now;
    char time_str[9];
    char date_str[11];
    char battery_status[32];
    int battery_capacity;
    char capacity_str[8];
    
    // 定义颜色
    unsigned char low_color_r = 255, low_color_g = 0, low_color_b = 0;    // 红色 (<10%)
    unsigned char mid_color_r = 255, mid_color_g = 255, mid_color_b = 0;  // 黄色 (10%-80%)
    unsigned char high_color_r = 0, high_color_g = 255, high_color_b = 0;  // 绿色 (>80%)
    
    while (1) {
        now = time(NULL);
        tm_now = localtime(&now);
        
        strftime(time_str, sizeof(time_str), "%H:%M:%S", tm_now);
        strftime(date_str, sizeof(date_str), "%Y-%m-%d", tm_now);
        const char* weekday_str = get_chinese_weekday(tm_now->tm_wday);
        
        // 读取电池状态
        if (read_battery_status(battery_status, &battery_capacity) == 0) {
            snprintf(capacity_str, sizeof(capacity_str), "%d%%", battery_capacity);
        } else {
            strcpy(battery_status, "Unknown");
            strcpy(capacity_str, "N/A");
        }
        
        fb_clear_back_buffer(fb, 0, 0, 0);
        
        // 绘制时间
        draw_text(fb, fr, time_str, 0, 0, 255, 255, 255, 28, 0);
        draw_text(fb, fr, date_str, 0, 56, 255, 255, 255, 12, 0);
        // 绘制中文星期
        draw_text(fb, fr, weekday_str, 125, 60, 255, 255, 255, 9, 1);
        
        // 绘制电池状态 (右上角)
        int battery_x = fb->width - 100;
        int battery_y = 10;
        
        // 根据电量百分比选择颜色
        unsigned char r, g, b;
        if (battery_capacity < 10) {
            r = low_color_r;
            g = low_color_g;
            b = low_color_b;
        } else if (battery_capacity > 80) {
            r = high_color_r;
            g = high_color_g;
            b = high_color_b;
        } else {
            r = mid_color_r;
            g = mid_color_g;
            b = mid_color_b;
        }
        
        // 绘制电量百分比
        draw_text(fb, fr, capacity_str, battery_x + 60, battery_y + 60, r, g, b, 11, 0);
        
        // 如果是充电状态，在坐标(0,60)显示充电图标
        if (strcmp(battery_status, "Charging") == 0 && charging_icon) {
            draw_image(fb, charging_icon, 0, 81);
        }
        
        fb_update_screen(fb);
        
        // 睡眠到下一秒开始
        sleep(1 - (now % 1));
    }
}

int main(int argc, char *argv[]) {
    FrameBuffer fb;
    FontRenderer fr;
    Image *charging_icon = NULL;
    Image *battery_icon = NULL;
    
    if (fb_init(&fb, "/dev/fb0") < 0) {
        return 1;
    }
    
    // 只需要传入英文字体路径，中文字体会自动查找
    if (font_init_debug(&fr, "./wwDigital.ttf") < 0) {
        fb_close(&fb);
        return 1;
    }
    
    // 检查中文字体是否加载成功
    if (fr.chinese_face == NULL) {
        fprintf(stderr, "警告: 无法加载中文字体，星期显示可能不正常\n");
    }
    
    // 加载图标
    charging_icon = load_png("1.png");
    battery_icon = load_png("2.png");
    
    show_time_and_battery(&fb, &fr, charging_icon, battery_icon);
    
    free_image(charging_icon);
    free_image(battery_icon);
    font_close(&fr);
    fb_close(&fb);
    return 0;
}